package com.canbot.u05.activity.customvoice

import android.animation.ObjectAnimator
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.view.View
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.*
import com.canbot.u05.activity.customvoice.adapter.CustomDialogAddAnswerAdapter
import com.canbot.u05.activity.customvoice.bean.AnswerBean
import com.canbot.u05.activity.customvoice.bean.CustomAudioData
import com.canbot.u05.activity.customvoice.bean.CustomDialogExcelDatas
import com.canbot.u05.activity.customvoice.tool.CustomDialogAudioView
import com.canbot.u05.activity.customvoice.tool.CustomDialogSuccessView
import com.canbot.u05.activity.customvoice.tool.CustomDialogTextToSpeechView
import com.canbot.u05.bean.JsonResponse
import com.canbot.u05.socket.IpMsgConst
import com.canbot.u05.socket.MsgSendUtils
import com.canbot.u05.socket.MsgType
import com.canbot.u05.utils.OkHttpUtils
import com.canbot.u05.utils.PathConst
import com.canbot.u05.view.RouteRecordDialog
import com.canbot.u05.view.UsherModeRecordDialog
import com.canbot.u05.widget.LoadingDialogUtils
import kotlinx.android.synthetic.main.activity_custom_dialog_add_answer.*
import java.io.File
import java.util.*
import kotlin.collections.ArrayList

/**
 * CustomDialogAddAnswerActivity
 *
 * @author  Liu.Heng
 * @date  2019/5/29
 */
class CustomDialogAddAnswerActivity : BaseActivityNoTitle() {

    private lateinit var customDialogAddAnswerAdapter: CustomDialogAddAnswerAdapter

    private lateinit var mAnswerBeanList: MutableList<AnswerBean>

    private lateinit var dialogLoading: Dialog

    private lateinit var usherModeRecordDialog: RouteRecordDialog

    private lateinit var fileName: String

    private var currentPosition = -1

    private lateinit var customDialogExcelDatas: CustomDialogExcelDatas

    private lateinit var soundPath: String


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_custom_dialog_add_answer)
        initView()
    }

    override fun onResume() {
        super.onResume()
        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_tpdz_001.wav")
        MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "12")
    }

    fun initView() {
        val intent = intent
        customDialogExcelDatas = JSON.parseObject(intent.getStringExtra("data"), CustomDialogExcelDatas::class.java)
        mAnswerBeanList = customDialogExcelDatas.listAsBean
        if (mAnswerBeanList.isNotEmpty()) {
            my_save.visibility = View.VISIBLE
        }
        answer_recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        customDialogAddAnswerAdapter = CustomDialogAddAnswerAdapter(this, mAnswerBeanList,
                object : CustomDialogAddAnswerAdapter.Callback {

                    override fun clickEvent(position: Int, view: View) {
                        currentPosition = position
                        when (view.id) {
                            R.id.answer_relativeLayout_item -> {
                                if (mAnswerBeanList[position].type == 1) {
                                    gotoCustomDialogTextToSpeechView(mAnswerBeanList[position].ttstext ,position)
                                } else {
                                    soundPath = mAnswerBeanList[position].soundpath
                                    getAudios(position)
                                }
                            }
                            /**选择图片*/
                            R.id.my_imageView1 -> {
                                val intent1 = Intent(this@CustomDialogAddAnswerActivity, CustomDialogAddPicActivity::class.java)
                                intent1.putExtra("picPath", mAnswerBeanList[position].imgpath)
                                startActivityForResult(intent1, 10001)
                                overridePendingTransitionExt()
                                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_dztp_001.wav")
                                MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "29")
                                MsgSendUtils.sendStringMsg(MsgType.ACTION, "14007")
                            }
                            /**默认动作*/
                            R.id.my_relativeLayout -> {
                                mAnswerBeanList[currentPosition].actionid = ""
                                customDialogAddAnswerAdapter.notifyDataSetChanged()
                            }
                            /**指定动作*/
                            R.id.my_relativeLayout1 -> {
                                val intent2 = Intent(this@CustomDialogAddAnswerActivity, CustomDialogAddActionActivity::class.java)
                                intent2.putExtra("actionId", mAnswerBeanList[position].actionid)
                                startActivityForResult(intent2, 10002)
                                overridePendingTransitionExt()
                            }
                            /**删除回答*/
                            R.id.delete1 -> {
                                mAnswerBeanList.removeAt(position)
                                customDialogAddAnswerAdapter.removeItem(position)
                                if (mAnswerBeanList.isEmpty()) {
                                    my_save.visibility = View.GONE
                                }
                            }
                            else -> {

                            }
                        }

                    }
                }
        )
        answer_recyclerView.adapter = customDialogAddAnswerAdapter


        my_back.setOnClickListener(::onClick)
        my_save.setOnClickListener(::onClick)
        add_answer.setOnClickListener(::onClick)
        my_icon1.setOnClickListener(::onClick)
        my_icon2.setOnClickListener(::onClick)
        my_icon3.setOnClickListener(::onClick)
    }

    /**
     * 进入录音
     */
    private fun record() {
        /**点击语音录入图标*/
        usherModeRecordDialog = RouteRecordDialog(this, RouteRecordDialog.DIALOG_MODE)
        usherModeRecordDialog.setFinishClickListener(::onClick)
        usherModeRecordDialog.setCancleClickListener(::onClick)
        setDialogWindowAttr(usherModeRecordDialog, this)
        usherModeRecordDialog.show()
    }

    fun setDialogWindowAttr(dlg: Dialog, ctx: Context) {
        val sizeX = ctx.resources.getDimension(R.dimen.px1000) + ctx.resources.getDimension(R.dimen.px156)
        val sizeY = ctx.resources.getDimension(R.dimen.px744)
        dlg.setCancelable(false)
        val window = dlg.window
        if (window != null) {
            val lp = window.attributes
            lp.gravity = Gravity.CENTER
            /**宽高可设置具体大小*/
            lp.width = sizeX.toInt()
            lp.height = sizeY.toInt()
            window.attributes = lp
        }
    }

    private fun onClick(view: View) {
        when (view.id) {
            /**返回*/
            R.id.my_back -> {
                finish()
                overridePendingTransitionExt()
            }
            /**保存*/
            R.id.my_save -> {
                loge("${JSON.parseObject(intent.getStringExtra("data"), CustomDialogExcelDatas::class.java).listAsBean.size}")
                if (JSON.parseObject(intent.getStringExtra("data"), CustomDialogExcelDatas::class.java).listAsBean.isEmpty()) {
                    updateData()
                    loge("添加")
                } else {
                    changeData()
                    loge("修改")
                }
            }
            /**添加*/
            R.id.add_answer -> {
                if (add_text.text.contains("添加")) {
                    add_text.text = "隐藏"
                    add_answer.background = ContextCompat.getDrawable(this, R.drawable.custom_dialog2_answer_hidden)
                    resources.getDrawable(R.drawable.custom_dialog2_answer_hidden, null)
                    val objectAnimator = ObjectAnimator.ofFloat(answer_relativeLayout, "translationY", 0F, -relativeLayout2.measuredHeight.toFloat())
                    objectAnimator.duration = 0
                    objectAnimator.start()
                } else {
                    add_text.text = "添加"
                    add_answer.background = ContextCompat.getDrawable(this, R.drawable.custom_dialog2_answer_add)
                    /** 通过构造器 并且 传递 需要移动的参数*/
                    val objectAnimator = ObjectAnimator.ofFloat(answer_relativeLayout, "translationY", 0F)
                    objectAnimator.duration = 0
                    objectAnimator.start()
                }
            }
            /**文本转语音*/
            R.id.my_icon1 -> {
                if (mAnswerBeanList.size > 9) {
                    showToast("回答数量已达上限了")
                    return
                }
                gotoCustomDialogTextToSpeechView("", -1)
            }
            /**录音*/
            R.id.my_icon2 -> {
                if (mAnswerBeanList.size > 9) {
                    showToast("回答数量已达上限了")
                    return
                }
                record()
            }
            /**音频*/
            R.id.my_icon3 -> {
                if (mAnswerBeanList.size > 9) {
                    showToast("回答数量已达上限了")
                    return
                }
                soundPath = ""
                getAudios(-1)
            }
            /**录音确认*/
            R.id.record_dialog_finish -> {
                fileName = usherModeRecordDialog.ok()
                loge("fileName$fileName")
                usherModeRecordDialog.setTime(this@CustomDialogAddAnswerActivity.getString(R.string.uploading_please_wait))
                loge("录音的文件名：$fileName")
                uploadFile()
            }
            /**录音取消*/
            R.id.record_dialog_cancle -> {
                usherModeRecordDialog.no()
                usherModeRecordDialog.dismiss()
            }
            else -> {
            }
        }
    }

    /**上传到机器人头部的某个文件夹下*/
    private val url = IpMsgConst.HTTP_URL + "uploadRecord"

    private fun uploadFile() {
        val hashMap = HashMap<String, Any>()
        hashMap["audiofile"] = File(UsherModeRecordDialog.RECORD_FILE_DIR, fileName)
        hashMap["path"] = fileName
        hashMap["dialog"] = "dialog"
        OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                loge(result + "上传成功")
                runOnUiThread {
                    val path = fileName
                    my_save.visibility = View.VISIBLE
                    usherModeRecordDialog.cancel()
                    showToast(getString(R.string.upload_complete))
                    loge("录音文件路径 ：$path")
                    val answerBean = AnswerBean()
                    answerBean.soundpath = "/uusound/$path"
                    answerBean.type = 0
                    mAnswerBeanList.add(answerBean)
                    notifyData()
                    loge("路径----->$path")
                }
            }

            override fun onFailure() {

                runOnUiThread {
                    usherModeRecordDialog.cancel()
                    showToast(getString(R.string.upload_failed))
                }
            }
        })
    }


    /***
     * 获取音频文件
     */
    private fun getAudios(type: Int) {

        /**http://192.168.12.103:7755/getAudioList*/
        dialogLoading = LoadingDialogUtils.createLoadingDialog(this@CustomDialogAddAnswerActivity, resources.getString(R.string.request))
        dialogLoading.show()
        val url = "http://" + IpMsgConst.HEAD_SOCKET_HOST + ":7755/getAudioList"
        val hashMap = HashMap<String, String>()
        hashMap["path"] = "/uusound"
        OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {

            override fun onSuccess(result: String) {
                loge("result=$result")
                val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)
                loge("onSuccess:" + "http://" + IpMsgConst.HEAD_SOCKET_HOST + ":7755/" + "strMsgBean.getRc()" + strMsgBean.rc)
                if (strMsgBean.rc == 0) {
                    runOnUiThread {
                        val mCustomAudioData: MutableList<CustomAudioData> = ArrayList()
                        dialogLoading.setCancelable(true)
                        dialogLoading.dismiss()
                        val list = JSON.parseArray(strMsgBean.result.toString(), CustomAudioData::class.java)

                        list.sortWith(Comparator { audio, t1 -> audio.name.compareTo(t1.name) })
                        if (list.isEmpty()) {
                            showToast("当前无音频文件")
                        } else {
                            mCustomAudioData.addAll(list)
                            gotoCustomDialogAudioView(mCustomAudioData, type)
                        }
                    }
                }
            }

            override fun onFailure() {
                runOnUiThread {
                    dialogLoading.dismiss()
                    showToast(getString(R.string.network_error))
                }
            }
        })
    }


    private fun gotoCustomDialogTextToSpeechView(answer: String, position: Int) {
        CustomDialogTextToSpeechView(this, answer,
                object : CustomDialogTextToSpeechView.OnCloseListener {

                    override fun callBack(dialog: Dialog, confirm: Boolean, string: String) {
                        if (confirm && string.isNotEmpty()) {
                            my_save.visibility = View.VISIBLE
                            val answerBean = AnswerBean()
                            answerBean.ttstext = string
                            answerBean.type = 1
                            mAnswerBeanList.add(answerBean)
                            notifyData()
                            dialog.dismiss()
                        }
                    }

                    override fun callBackPosition(dialog: Dialog, position: Int, string: String) {
                        if (string.isNotEmpty()) {
                            mAnswerBeanList[position].ttstext = string
                            customDialogAddAnswerAdapter.notifyDataSetChanged()
                            dialog.dismiss()
                        }
                    }
                }, position).show()

    }

    private fun gotoCustomDialogAudioView(mCustomAudioData: MutableList<CustomAudioData>, type: Int) {
        CustomDialogAudioView(this@CustomDialogAddAnswerActivity, mCustomAudioData, soundPath,
                object : CustomDialogAudioView.OnCloseListener {

                    override fun onClick(dialog: Dialog, confirm: Boolean, audioPath: String?) {
                        if (confirm && audioPath.isNotEmpty2()) {
                            my_save.visibility = View.VISIBLE
                            val answerBean = AnswerBean()
                            answerBean.soundpath = audioPath
                            answerBean.type = 0
                            mAnswerBeanList.add(answerBean)
                            notifyData()
                            dialog.dismiss()
                        }
                    }

                    override fun onClickPosition(dialog: Dialog, position: Int, audioPath: String?) {
                        mAnswerBeanList[position].soundpath = audioPath ?: ""
                        customDialogAddAnswerAdapter.notifyDataSetChanged()
                        dialog.dismiss()
                    }

                }, type).show()
    }

    private fun notifyData() {
        customDialogAddAnswerAdapter.notifyItemInserted(mAnswerBeanList.size)
        answer_recyclerView.scrollToPosition(mAnswerBeanList.size - 1)
    }


    private fun updateData() {
        dialogLoading = LoadingDialogUtils.createLoadingDialog(this, resources.getString(R.string.request))
        dialogLoading.show()
        val hasMap = HashMap<String, Any>()
        hasMap["type"] = "0"
        hasMap["questions"] = JSON.toJSONString(customDialogExcelDatas.listQsBean)
        hasMap["answers"] = JSON.toJSONString(mAnswerBeanList)

        loge("${customDialogExcelDatas.listQsBean}")
        loge("$mAnswerBeanList")

        OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "dialogcustom", hasMap, object : OkHttpUtils.OkHttpCallBack, CustomDialogSuccessView.OnCloseListener {
            override fun onClick(dialog: Dialog, confirm: Boolean) {
                dialog.dismiss()
                val intent = Intent(this@CustomDialogAddAnswerActivity, CustomDialogMainActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                startActivity(intent)
                finish()
                overridePendingTransitionExt()
            }

            override fun onSuccess(result: String) {
                val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)

                if (strMsgBean.rc == 0) {
                    runOnUiThread {
                        dialogLoading.dismiss()
                        val customDialogSuccessView = CustomDialogSuccessView(this@CustomDialogAddAnswerActivity, this)
                        customDialogSuccessView.show()
                        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_dzcg_001.wav")
                        MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "30")
                        MsgSendUtils.sendStringMsg(MsgType.ACTION, "14007")
                    }
                }
            }

            override fun onFailure() {
                runOnUiThread {
                    dialogLoading.dismiss()
                    showToast(getString(R.string.network_error))
                }
            }
        })
    }

    private fun changeData() {
        dialogLoading = LoadingDialogUtils.createLoadingDialog(this, resources.getString(R.string.request))
        dialogLoading.show()
        val hasMap = HashMap<String, Any>()
        hasMap["type"] = "8"
        hasMap["data"] = JSON.toJSONString(CustomDialogExcelDatas(customDialogExcelDatas.listQsBean, mAnswerBeanList))

        loge("${customDialogExcelDatas.listQsBean}")
        loge("$mAnswerBeanList")

        OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "dialogcustom", hasMap, object : OkHttpUtils.OkHttpCallBack, CustomDialogSuccessView.OnCloseListener {
            override fun onClick(dialog: Dialog, confirm: Boolean) {
                dialog.dismiss()
                val intent = Intent(this@CustomDialogAddAnswerActivity, CustomDialogMainActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                startActivity(intent)
                finish()
            }

            override fun onSuccess(result: String) {
                val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)

                if (strMsgBean.rc == 0) {
                    runOnUiThread {
                        dialogLoading.dismiss()
                        val customDialogSuccessView = CustomDialogSuccessView(this@CustomDialogAddAnswerActivity, this)
                        customDialogSuccessView.show()
                    }
                }
            }

            override fun onFailure() {
                runOnUiThread {
                    dialogLoading.dismiss()
                    showToast(getString(R.string.network_error))
                }
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 10001 && resultCode == Activity.RESULT_OK && data != null) {
            val str = data.getStringExtra("picPath")
            if (str.isNotEmpty()) {
                mAnswerBeanList[currentPosition].imgpath = str
                customDialogAddAnswerAdapter.notifyDataSetChanged()
            }
        } else if (requestCode == 10002 && resultCode == Activity.RESULT_OK && data != null) {
            val str = data.getStringExtra("actionId")
            if (str.isNotEmpty()) {
                mAnswerBeanList[currentPosition].actionid = str
                customDialogAddAnswerAdapter.notifyDataSetChanged()
            }
        } else {
            return
        }
    }

}
